//屏幕驱动

#ifndef _DSP_DEV_H_
#define _DSP_DEV_H_

#include <TFT_eSPI.h>
#include <lvgl.h>

#include "main.h"

// LCD屏幕初始化
TFT_eSPI tft = TFT_eSPI();  // Invoke custom library

static void disp_init(void);
static void disp_flush(lv_disp_drv_t *disp_drv, const lv_area_t *area,
                       lv_color_t *color_p);

/* Initialize your display and the required peripherals. */
static void disp_init(void) {
  // LCD屏幕初始化
  tft.init();
  tft.setRotation(1);
  tft.fillScreen(TFT_WHITE);
  tft.setTextSize(1);
  tft.setTextColor(TFT_MAGENTA);
  tft.setCursor(0, 0);
  tft.setTextDatum(MC_DATUM);
  tft.setTextSize(1);
  tft.setSwapBytes(true);
  //显示屏背光
  ledcSetup(10, 1000 /*freq*/, 10 /*resolution*/);
  ledcAttachPin(TFT_BL, 10);
  analogReadResolution(10);
  ledcWrite(10, 512);
}

void lv_port_disp_init(void) {
  disp_init();

  static lv_disp_draw_buf_t draw_buf_dsc_1;
  static lv_color_t buf_1[screenWidth * 10]; /*A buffer for 10 rows*/
  static lv_color_t buf_2[screenWidth * 10]; /*An other buffer for 10 rows*/
  lv_disp_draw_buf_init(&draw_buf_dsc_1, buf_1, buf_2,
                        screenWidth * 10); /*Initialize the display buffer*/

  // static lv_disp_draw_buf_t draw_buf;
  // static lv_color_t buf[screenWidth * 10];
  // lv_disp_draw_buf_init(&draw_buf, buf, NULL, screenWidth * 10);

  /*-----------------------------------
   * Register the display in LVGL
   *----------------------------------*/

  static lv_disp_drv_t disp_drv; /*Descriptor of a display driver*/
  lv_disp_drv_init(&disp_drv);   /*Basic initialization*/
  if (tft.getRotation() % 2 == 0) {
    disp_drv.hor_res = screenHeight;
    disp_drv.ver_res = screenWidth;
  } else {
    disp_drv.hor_res = screenWidth;
    disp_drv.ver_res = screenHeight;
  }
  disp_drv.flush_cb = disp_flush;
  disp_drv.draw_buf = &draw_buf_dsc_1;
  // disp_drv.draw_buf = &draw_buf;
  lv_disp_drv_register(&disp_drv);
}

/* Display flushing */ /*显示驱动*/
void disp_flush(lv_disp_drv_t *disp, const lv_area_t *area,
                lv_color_t *color_p) {
  uint16_t c;
  // static int dis_cotter = 0;

  tft.startWrite(); /* Start new TFT transaction */
  tft.setAddrWindow(area->x1, area->y1, (area->x2 - area->x1 + 1),
                    (area->y2 - area->y1 + 1)); /* set the working window */
  // for (int y = area->y1; y <= area->y2; y++) {
  //   for (int x = area->x1; x <= area->x2; x++) {
  //     c = color_p->full;
  //     tft.writeColor(c, 1);
  //     color_p++;
  //   }
  // }
  uint32_t w = (area->x2 - area->x1 + 1);
  uint32_t h = (area->y2 - area->y1 + 1);
  tft.pushColors((uint16_t *)&color_p->full, w * h, true);
  tft.endWrite(); /* terminate TFT transaction */

  // Serial.printf("刷新显示中：%d \n\r", dis_cotter++);
  lv_disp_flush_ready(disp); /* tell lvgl that flushing is done */
}

#endif